package com.dingdang.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dingdang.data.Result;
import com.dingdang.em.ResultEnum;
import com.dingdang.entity.TbAdvertise;
import com.dingdang.mapper.TbAdvertiseMapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 广告表
 前端控制器
 * </p>
 *
 * @author author
 * @since 2021-12-19
 */
@RestController
@EnableScheduling
public class TbAdvertiseController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TbAdvertiseMapper advertiseMapper;

    //前台广告推送服务,一天一更,因为广告属于热点数据大量访问请求可能会导致服务器压力过大,所以使用redis存储这些热点数据


    @Scheduled(cron = "0 * * * * ?")
    public void autoUpdate(){
        redisTemplate.delete("adver");
    }

    @GetMapping
    @ResponseBody
    @ApiOperation(value = "广告推送")
    public Result adverPush(){
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        if (!redisTemplate.hasKey("adver")){
            List<TbAdvertise> list = getList();
            redisTemplate.opsForList().rightPush("adver",list);
            List advertises = redisTemplate.opsForList().range("adver",0,-1);
            return Result.response(ResultEnum.SUCCESS).setData(list);
        }
        List advertises = redisTemplate.opsForList().range("adver",0,-1);
        return Result.response(ResultEnum.SUCCESS).setData(advertises);
    }

    public List<TbAdvertise> getList(){
        LambdaQueryWrapper<TbAdvertise> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.le(TbAdvertise::getStartTime, LocalDate.now()).ge(TbAdvertise::getEndTime,  LocalDate.now());
        return advertiseMapper.selectList(lambdaQuery);
    }
}
